package vip.mall.core.handler;

import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import vip.mall.common.enums.CommonResponseCode;
import vip.mall.common.exception.CommonException;
import vip.mall.common.result.CommonResult;

import java.util.Objects;

/**
 * @author ASUS
 * @Date 2025/2/13 10:04
 * @Descripition 统一异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 参数校验异常
     * @return 异常处理结果
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult methodArgumentNotValidException(MethodArgumentNotValidException e) {
        return CommonResult.error(CommonResponseCode.REQUEST_PARAMS_VALIDATION_ERROR, Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
    }

    /**
     *  404异常处理
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public CommonResult noHandlerFoundException() {
        return CommonResult.error(CommonResponseCode.NOT_FOUND);
    }
    /**
     *  通用异常处理
     */
    @ExceptionHandler(CommonException.class)
    public CommonResult commonExceptionHandler(CommonException e) {
        return CommonResult.error(e.getCommonResponseCode().getCode(),e.getMessage());
    }
}
